/**
 * Copyright (c) 2019-2021,  陈俊兵 (cjb6b.com@gmail.com)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.itrip.config;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.solr.SolrProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Optional;

/**
 *
 * @packageName com.itrip.search.config
 * @fileName SolrConfig.java
 * @author 陈俊兵 (cjb6b.com@gmail.com)
 * @createTime 2020/9/15 18:51
 * @lastModify 2020/9/15 18:51
 * @version 1.0.0
 */
@Configuration
@ConditionalOnClass({ HttpSolrClient.class, CloudSolrClient.class })
@EnableConfigurationProperties(SolrProperties.class)
public class SolrConfig {

    private final SolrProperties properties;

    private SolrClient solrClient;

    public SolrConfig(SolrProperties properties) {
        this.properties = properties;
    }
    @Bean
    public SolrClient solrClient() {
        return createSolrClient();
    }

    private SolrClient createSolrClient() {
        if (StringUtils.hasText(this.properties.getZkHost())) {
            return new CloudSolrClient.Builder(Arrays.asList(this.properties.getZkHost()), Optional.empty()).build();
        }
        return new HttpSolrClient.Builder(this.properties.getHost()).withResponseParser(new XMLResponseParser()).build();
    }

}
